package handle

import (
	"gitee.com/crack007/api-throttling/common/middleware"
	"gitee.com/crack007/api-throttling/config"
	"gitee.com/crack007/api-throttling/controller"
	"gitee.com/crack007/api-throttling/service"
	"gitee.com/crack007/goose/core/web"
)

type apiServerHandle struct {
	web.DefaultHttpServerHandle
	router *config.RouteListConfig
}

func NewApiServerHandle() *apiServerHandle {
	return &apiServerHandle{
		router: config.NewRouteListConfig(),
	}
}

func (h *apiServerHandle) OnInitRouter() {
	webServer := h.GetHttpServer()
	for _, r := range h.router.RouteList {
		apiService := service.NewApiService(r)
		service.ApiManager.AddRoute(apiService)
		webServer.Engine.Handle(r.Method, r.Path, apiService.HandleRequest)
	}
	c := &controller.ApiController{}
	gmGroup := webServer.Engine.Group("/_gm", middleware.JsonResponseMiddleware)
	gmGroup.POST("/user", web.Action(c.AddUser))
	gmGroup.DELETE("/user", web.Action(c.DelUser))
	gmGroup.PUT("/user", web.Action(c.UpdateUser))
}

func (h *apiServerHandle) OnInitConfig() {
	h.router = config.InitRoute()
}
